import { sm3 } from "sm-crypto";

class CryptoSM3 {
  chunks = [] as string[];
  param = {};

  static create(param: any) {
    return new CryptoSM3(param);
  }

  constructor(param = {}) {
    this.param = param;
  }

  update(data: Uint8Array) {
    const chunkHash = sm3(data);
    this.chunks.push(chunkHash);
  }
  finalize(): string {
    if (this.chunks.length == 1) {
      //console.log(this.chunks[0]);
      return this.chunks[0];
    }
    let all = new Uint8Array();
    for (let i = 0; i < this.chunks.length; i++) {
      const array2: Uint8Array = this.hexStringToUint8Array(this.chunks[i]);
      all = Uint8Array.from([...all, ...array2]);
    }
    const finalHash = sm3(all);
    //console.log(finalHash);
    return finalHash;
  }

  hexStringToUint8Array(hexStr: string): Uint8Array {
    if (hexStr.length % 2 !== 0) {
      throw new Error("Hex string must have an even length");
    }

    const len = hexStr.length / 2;
    const uint8Array = new Uint8Array(len);

    for (let i = 0; i < len; i++) {
      const byte = parseInt(hexStr.substr(i * 2, 2), 16);
      if (isNaN(byte)) {
        throw new Error("Invalid hex digit");
      }
      uint8Array[i] = byte;
    }

    return uint8Array;
  }
}

export default CryptoSM3;
